import React, { useCallback, useMemo, useState } from 'react'
import Test from './Test';
import Button from './Button';

export default function MemoCom() {
  let [count, setCount] = useState(0);
  let [arr, setArr] = useState([1,2,3,4,5,6,7,8]);
  //声明一个函数
  let add = useCallback(() => {
    setCount(v => v + 1);
  }, []);
  //useMemo hook 函数 可以缓存一个结果值
  let t = useMemo(() => {
    //在函数中计算数组元素的和
    let total = 0;
    //测试是否再次执行
    console.log('计算 run');
    arr.forEach(item => {
      total += item;
    });
    //返回总和
    return total;
  }, [arr]);


  return (
    <div>
      <h2>{count}</h2>
      <Button add={add} />
      <Test  />
      <hr />
      <h2>数组元素的和: {t}</h2>
      <button onClick={() => {
        setArr([...arr, 10])
      }}>数组新增元素</button>
    </div>
  )
}
